package com.cmcc.shared.widget


import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.shared.R
import com.cmcc.shared.SdkManager
import com.cmcc.shared.databinding.FragmentCardDriverBinding
import com.cmcc.shared.model.Coordinates
import com.cmcc.shared.utils.*
import com.cmcc.shared.viewModel.SharedViewModel
import com.cmcc.shared.widget.dialog.AppAlertDialog
import kotlinx.android.synthetic.main.widget_card_driver.view.*


/**
 * Author: caixing
 * Date: 2019/12/3
 * Description:
 */
class DriverCardFragment : Fragment() {

    private lateinit var viewModel: SharedViewModel
    private lateinit var binding: FragmentCardDriverBinding

    private var workStatus: Int = 0 //司机工作状态：0：休班中 1：上班中
    private var coordinates: Coordinates = Coordinates(114.043065, 22.670016)


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentCardDriverBinding.inflate(inflater, container, false)
        viewModel = ViewModelProviders.of(this).get(SharedViewModel::class.java)
        L.d("----------------DriverCardFragment--onCreateView SharedViewModel: " + viewModel.hashCode())
        L.d("----------------DriverCardFragment--onCreateView")
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        L.e("----------------DriverCardFragment--onViewCreated")
        initEvent()
        initObserver()
    }

    override fun onResume() {
        super.onResume()
        initView()
    }

    private fun initView() {
        when(SdkManager.getLanguage()){
            0->{
                binding.driver.card_title.text = "Orders"
                binding.driver.today_income_title.text = "Flowing today"
                binding.driver.today_deals.text = "Total orders today"
                binding.driver.changeStatus.text = "Take an order"
            }
            1->{
                binding.driver.card_title.text = "接单"
                binding.driver.today_income_title.text = "今日流水"
                binding.driver.today_deals.text = "今日订单总数"
                binding.driver.changeStatus.text = "去接单"
            }
            2->{
                binding.driver.card_title.text = "接單"
                binding.driver.today_income_title.text = "今日流水"
                binding.driver.today_deals.text = "今日訂單總數"
                binding.driver.changeStatus.text = "去接單"
            }
        }
        binding.driver.changeStatus(workStatus)
    }

    private fun initEvent() {
        binding.driver.failedLayout.clickWithTrigger {
            SdkManager.logicHandler.let { it!!.tokenExpire() }
        }
        binding.driver.successLayout.clickWithTrigger {
            val token = TokenUtils.getUserToken()
            if (!token.isNullOrEmpty()) {
                if (workStatus == 0) {
                    Toast.makeText(
                        context,
                        getString(R.string.driver_off_work_tip),
                        Toast.LENGTH_LONG
                    )
                        .show()
                } else {
                    navigationToDriverMain()
                }
            } else {
                SdkManager.logicHandler.let { it!!.tokenExpire() }
            }
        }
        binding.driver.setStatusChangeClickListener(View.OnClickListener {
            if (workStatus == 1) {//上班中，想要休班需要看是否有进行中的订单
                val token = TokenUtils.getUserToken()
                if (!token.isNullOrEmpty()) {
                    viewModel.queryOrderProgress(token)
                } else {
                    SdkManager.logicHandler.let { it!!.tokenExpire() }
                }
            } else {
                //检查工作状态
                changeWorkStatus()
            }
        })
    }

    /**
     * 检查司机工作状态
     */
    private fun changeWorkStatus() {
        val token = TokenUtils.getUserToken()
        if (!token.isNullOrEmpty()) {
            viewModel.changeDriverStatus(
                token,
                if (workStatus == 0) 1 else 0,
                coordinates
            )
        } else {
            SdkManager.logicHandler.let { it!!.tokenExpire() }
        }
    }


    private fun initObserver() {
        SharedViewModel.loginToken.observe(this, Observer {
            L.d("----------passenger", "token")
            //当token  变化且不为空的时候 请求卡片信息
            it.token.let { token->
                binding.driver.loading()
                TokenUtils.setUserToken(token)
                //请求卡片信息
                viewModel.requestCardInfo(token)
            }

        })

        /**
         * 监听卡片的信息
         * 变化
         *
         */
        viewModel.carInfo.observe(this, Observer { cardInfo ->
            L.d("----------driver", "card")
            if (null != cardInfo && cardInfo.isDriver) {
                binding.driver.loadSuccess()
                workStatus = cardInfo.workStatus
                binding.driver.setValue(cardInfo.orderCountToday, cardInfo.totalAmountToday)
                binding.driver.changeStatus(workStatus)
            } else {
                binding.driver.loadFailed()
            }

        })

        viewModel.processOrder?.observe(this, Observer { order ->
            if (order == null) {//没有进行中的订单，可以更改状态为接单中
                changeWorkStatus()
            } else {
                Toast.makeText(
                    context!!,
                    getString(R.string.driver_has_doing_order_tip2),
                    Toast.LENGTH_LONG
                ).show()

            }
        })

        viewModel.driverWorkStatus.observe(this, Observer { data ->
            when (data.code) {
                200 -> {//更改状态成功
                    val token = TokenUtils.getUserToken()
                    if (!token.isNullOrEmpty()) {
                        viewModel.requestCardInfo(token)
                        if (workStatus == 0) {
                            workStatus = 1
                            navigationToDriverMain()

                            SpHelper.setParam(context!!,"Status","driver",true)
                        } else {
                            workStatus = 0
                            Toast.makeText(
                                context!!,
                                getString(R.string.shared_driver_off_work),
                                Toast.LENGTH_LONG
                            ).show()

                            SpHelper.setParam(context!!,"Status","driver",false)
                        }
                        binding.driver.changeStatus(workStatus)
                    }
                }
                1002 -> {
                    var dialog = AppAlertDialog(context!!)

                    dialog.setContent(getString(R.string.driver_need_to_set_car_card_tip))
                        .setNavigation("", null, false)
                        .setPositive(
                            getString(R.string.shared_to_set_tip),
                            View.OnClickListener {
                                ARouter.getInstance().build("/driver/taxi_information").navigation()
                            })
                        .show()
                }
                else -> {
                    Toast.makeText(
                        context!!,
                        data.msg,
                        Toast.LENGTH_LONG
                    ).show()
                }
            }
        })
    }

    private fun navigationToDriverMain() {
        ARouter.getInstance().build("/driver/main").navigation()
    }



}